package com.jms.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * create by yongli on 2021-06-11 15:29
 */
@Configuration
public class NewRedisConfig {


    private static Logger logger = LoggerFactory.getLogger(NewRedisConfig.class);

    // spring中自动注入该对象
    @Autowired
    private LettuceConnectionFactory redisConnectionFactory;


    // 两个会影响
    public RedisConnectionFactory getConnectionFactory() {
        logger.info("redis-----info, host:{}, port:{}, database:{}, password:{}",
                redisConnectionFactory.getHostName(),
                redisConnectionFactory.getPort(),
                redisConnectionFactory.getDatabase(),
                redisConnectionFactory.getPassword());

        return null;
    }


    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory cf) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(cf);
        return stringRedisTemplate;
    }


    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory).build();
    }


    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> rest = new RedisTemplate<>();

        rest.setKeySerializer(new StringRedisSerializer());
        rest.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        rest.setConnectionFactory(redisConnectionFactory);
        rest.afterPropertiesSet();
        return rest;
    }
}
